import { Rules } from "async-validator";
import { Context, Next } from "koa";
import validate from "../utils/validator";
import { access, sql } from "../logger";
import { callbackData } from "../utils/data.handler";
import dictService from "../service/dict.service";


export const DictTypeValidator = async (ctx: Context, next: Next) => {
    const rules: Rules = {
        name: {
            type: 'string',
            required: true,
            message: '名称不能为空'
        },
        code: {
            type: 'string',
            required: true,
            message: '编码不能为空'
        }
    }

    const { error } = await validate<any>(ctx, rules);
    if (error) {
        access.info('字典信息校验错误', { msg: error })
        console.error('字典信息校验错误', { msg: error })
        ctx.app.emit('error', callbackData('1', error), ctx);
        return false;
    }
    await next();
}

export const DictDataValidator = async (ctx: Context, next: Next) => {
    const rules: Rules = {
        dict_label: {
            type: 'string',
            required: true,
            message: '名称不能为空'
        },
        dict_code: {
            type: 'string',
            required: true,
            message: '编码不能为空'
        },
        dict_value: {
            type: 'string',
            required: true,
            message: '值不能为空'
        }
    }

    const { error } = await validate<any>(ctx, rules);
    if (error) {
        access.info('字典信息校验错误', { msg: error })
        console.error('字典信息校验错误', { msg: error })
        ctx.app.emit('error', callbackData('1', error), ctx);
        return false;
    }
    await next();
}

//是否存在库 校验
export const verifyDict = async (ctx:Context,next:Next)=>{
    const {name='',code} = ctx.request.body || {};
    try{
        let res = await dictService.findTypeInfo({name,code});
        if(res){
            sql.error('字典查重错误',{name})
            console.error('字典已存在',{name})
            ctx.app.emit('error',callbackData('2','字典已存在'),ctx);
            return false;
        }
    }catch(err){
        sql.error('查询字典信息发生错误',err)
        console.error('获取字典信息错误',err)
        ctx.app.emit('error',callbackData('2','字典错误'),ctx);
        return false;
    }
    await next();
}

//是否存在值 校验
export const verifyDictData = async (ctx:Context,next:Next)=>{
    const {dict_label,dict_value,dict_code} = ctx.request.body || {};
    try{
        let res = await dictService.findDataInfo({dict_label,dict_value,dict_code});
        if(res){
            sql.error('字典值查重错误',{dict_label})
            console.error('字典值已存在',{dict_label})
            ctx.app.emit('error',callbackData('2','字典值已存在'),ctx);
            return false;
        }
    }catch(err){
        sql.error('查询字典信息发生错误',err)
        console.error('获取字典信息错误',err)
        ctx.app.emit('error',callbackData('2','字典错误'),ctx);
        return false;
    }
    await next();
}